package com.example.gobang.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.example.gobang.constant.Constants;
import com.example.gobang.model.Result;
import com.example.gobang.model.UserInfo;
import com.example.gobang.model.UserInfoVO;
import com.example.gobang.service.UserService;
import com.example.gobang.util.SecurityUtils;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param userName
     * @param password
     * @param session
     * @return
     */
    @PostMapping("/login")
    public Result<String> login(String userName, String password, String captcha, HttpSession session) {
        log.info("用户登录，获取到参数 userName:{}, password:{}, captcha:{}", userName, password, captcha);
        // 参数校验
        if(!StringUtils.hasLength(captcha)) {
            return Result.fail("验证码不能为空!");
        }
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail("用户名或密码为空！");
        }
        // 判定验证码是否正确
        String result = userService.isCorrectCaptcha(captcha, session);
        if(result != null) {
            return Result.fail(result);
        }

        // 根据用户名查询用户信息
        UserInfo userInfo = userService.selectByName(userName);
        if(userInfo == null) {
            return Result.fail("用户名或密码错误！");
        }
        // 判断密码是否正确
        if(!SecurityUtils.verity(password, userInfo.getPassword())) {
            return Result.fail("密码错误！");
        }
        // 将用户信息存储到 session 中
        session.setAttribute(Constants.USER_INFO, userInfo);
        return Result.success("登录成功！", Constants.LOGIN_SUCCESS);
    }

    /**
     * 获取用户信息
     * 从数据库中读取信息
     * @param session
     * @return
     */
    @GetMapping("/getUserInfo")
    public Result<UserInfoVO> getUserInfo(HttpSession session) {
        UserInfo userInfo = (UserInfo)session.getAttribute(Constants.USER_INFO);
        if(userInfo == null) {
            return Result.noLogin();
        }
        UserInfo newUserInfo = userService.selectById(userInfo.getUserId());
        UserInfoVO userInfoVO = UserInfoVO.getUserInfoVO(newUserInfo);
        return Result.success(userInfoVO, Constants.GET_USER_INFO);
    }

    /**
     * 获取验证码
     * @param session
     * @param response
     */
    @GetMapping("/getCaptcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response) {
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(Constants.CAPTCHA_WIDTH, Constants.CAPTCHA_HEIGHT, Constants.CAPTCHA_CODE_COUNT, Constants.CAPTCHA_THICKNESS);
        // 设置返回数据类型
        response.setContentType("image/jpeg");
        // 禁止使用缓存
        response.setHeader("Pragma", "No-cache");
        try {
            // 输出到页面
            captcha.write(response.getOutputStream());
            // 将 生成的验证码 和 验证码生成时间 存储到session中
            session.setAttribute(Constants.CAPTCHA_KEY, captcha.getCode());
            session.setAttribute(Constants.CAPTCHA_DATE, new Date());
            // 关闭流
            response.getOutputStream().close();
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 用户注册
     * @param userName
     * @param password
     * @return
     */
    @PostMapping("/register")
    public Result<String> register(String userName, String password) {
        log.info("用户注册，获取到参数 userName:{}, password: {}", userName, password);
        // 参数校验
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail("用户名或密码为空!");
        }
        try {
            String sqlPassword = SecurityUtils.encipher(password);
            int result = userService.insertUser(userName, sqlPassword);
            if(result > 0) {
                return Result.success("", Constants.REGISTER_SUCCESS);
            }
            return Result.fail("内部错误,请联系管理员");
        }catch (org.springframework.dao.DuplicateKeyException e){
            return Result.fail("用户名已存在!");
        }
    }
}
